package com.itlong.cloud.network.tcp.mina.manage;

import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.apache.mina.core.session.IoSession;

import java.util.HashMap;
import java.util.Map;

public class SessionManage {

	private static final Logger LOG = LoggerFactory.getLogger(SessionManage.class);
	private static SessionManage sessionMap = null;

	private Map<String, IoSession>map = new HashMap<String, IoSession>();


	//构造私有化 单例
	private SessionManage(){}


	public static SessionManage newInstance(){
		return SessionManageSingletonInstance.instance;
	}

	private static class SessionManageSingletonInstance{
		static SessionManage instance = new SessionManage();
	}

	/**
	 * @Description: 保存session会话
	 */
	public void addSession(String key, IoSession session){
		//LOG.info(String.format("当前会话列表：%s 准备添加一卡通项目:%s的会话：%s",map.values(),key,session.getRemoteAddress()));
		this.map.put(key, session);
	}
	/**
	 * @Description: 保存session会话
	 */
	public void delSession(String key){
		//LOG.info(String.format("当前会话列表：%s 准备移除一卡通项目:%s的会话", map.values(),key));
		this.map.remove(key);
	}
	/**
	 * @Description: 根据key查找缓存的session
	 */
	public IoSession getSession(String key){
		return this.map.get(key);
	}

	/**
	 * @Description: 发送消息到客户端
	 */
	public void sendMessage(String[] keys, Object message){
		for(String key : keys){
			sendMessage(key, message);
		}
	}
	/**
	 * @Description: 发送消息到客户端
	 */
	public AppErrorCodeEnum sendMessage(String key, Object message){
		IoSession session = getSession(key);

		if(session == null){
			return AppErrorCodeEnum.OPEN_DEFEATED;
		}
		session.write(message);
		return AppErrorCodeEnum.OPEN_SUCCESS;
	}

	/**
	 * <desc>
	 *     旧版APP_远程开门发送消息到一卡通
	 * </desc>
	 * @param key
	 * @param message
	 * @return
	 */
	public Code oldSendMessage(String key, Object message){
		IoSession session = getSession(key);
		if(session == null){
			return Code.YKL_NOLOGIN;
		}
		session.write(message);
		return Code.SUCCESS;
	}



}